// 这个要获取  企业微信这个应用 的 token
const getAuthToken = require("auth-token");
const { util, InsideErr } = require("utils");
const { Type_Qw_Mini } = require("../../constEnum.js");
const { Code2session } = require("./api.js");
const { proxyGetRequest } = require("request");

// 通过token 来解析 code
async function parseCodeByToken(token, code) {
    let [err, data] = await proxyGetRequest(Code2session)({
        access_token: token,
        grant_type: "authorization_code",
        js_code: code,
    });
    /*
    {
        "session_key": "wE6FPacKHyNjWCOvfjO1Qw==",
        "openid": "o6O8x5IkJb1jOm5y572eIcmKjR7Y",
        "unionid": "omYVS6kKAq6hcvdNbPFZHg1OyLSI"
    }
    */
    if (!util.nilValue(err)) {
        return [err, null];
    }
    let resData = data || {};
    if (!util.nilValue(resData.errcode) && resData.errcode !== 0) {
        let err = new InsideErr(resData);
        return [err, null];
    } else {
        return [null, resData];
    }
}

async function qwMiniLogin(appId, appSecret, code) {
    let [token_err, token_data] = await getAuthToken({
        tokenType: Type_Qw_Mini,
        appId,
        appSecret,
    });
    if (!util.nilValue(token_err)) {
        return [token_err, null];
    }
    // 拿到token 来解析 code
    return await parseCodeByToken(token_data, code);
}

module.exports = {
    qwMiniLogin,
};
